<template>
    <el-dialog title="添加标签" v-model="open" width="500px" label-width="auto">
        <el-form :model="formItem">
            <!-- <el-form-item label="添加标签人_id">
                <el-input v-model="formItem.creator"></el-input>
            </el-form-item> -->

            <el-form-item label="添加标签">
                <el-input v-model="formItem.name"></el-input>
            </el-form-item>
            <!-- <el-form-item label="编号">
                <el-input v-model="formItem._id"></el-input>
            </el-form-item> -->
            <!-- <el-form-item label="添加人">
                <el-input v-model="formItem.creatorId.name"></el-input>
            </el-form-item> -->
            <el-form-item label="最后修改时间">
                <el-input v-model="formItem.updateTime"></el-input>
            </el-form-item>

        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="open = false">取消</el-button>
                <el-button type="primary" @click="onConfirm">
                    确认
                </el-button>
            </div>
            {{ formItem }}
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue';
import { addTagsApi, detailTagsApi, updateTagsApi } from '@/api/manage'
import { useGlobalStore } from '../../store/global';
const open = ref(false)
const globalStore = useGlobalStore()
const formItem = ref({})
watch(open, () => {

    // 当弹窗打开时
    if (open.value && formItem.value._id) {
        detailTags();

    }
})
function onConfirm() {
    if (formItem.value._id) {
        updateTags();
    } else {
        addTags();

    }

}
function addTags() {
    addTagsApi({
        ...formItem.value, creatorId: globalStore.doctorInfo._id,
    }).then(res => {
        console.log(res);
        if (res.code == 200) {
            ElMessage({
                type: 'success',
                message: '添加成功'
            });
            open.value = false;
            emit('findTags')
        }
    })
}
function updateTags() {
    updateTagsApi(formItem.value)
        .then((res) => {
            if (res.code == 200) {
                ElMessage({
                    type: 'success',
                    message: '编辑成功'
                });
                open.value = false;
                emit('findTags')
            } else {
                ElMessage.error(res.message);
            }
        })


}
function detailTags() {
    detailTagsApi({
        _id: formItem.value._id
    }).then((res) => {
        if (res.code == 200) {
            formItem.value = res.data;
        }
    })
}
function openDialog(_id) {
    // 如果父组件传递了_id，说明要做修改
    console.log(_id);

    if (_id) {
        console.log(12);
        formItem.value._id = _id;
    } else {
        console.log(1);

        formItem.value = {}
    }
    open.value = true;
}
defineExpose({
    openDialog
})
const emit = defineEmits(['findTags'])
</script>

<style scoped></style>